<?php 
namespace  app\common\service;

use app\common\libs\sms\Main;
class SmsService{
	public static $instance = null;
	public  $config = array(
			"expire"=>"600",//短信验证码10分钟有效
			//发送短信类别
			"type" => array(
					"register",
					"forgetpwd",
			)
	);
	
	private function __construct(){
	}
	public static function getInstance(){
		if(self::$instance == null){
			self::$instance = new self();
		}
		return self::$instance;
	}
	
	
	public function setAdapter($channle){
		
		$this->adapter =  Main::getAdapter($channle);
		return $this;
	}
	
	/**
	 * 发送验证码
	 * @param unknown $tel
	 * @param unknown $type
	 */
	public function sendCode($tel,$type){
		if(!in_array($type, $this->config['type'])){
			return array("code"=>1,"message"=>"非法的短信发送请求");
		}
		$everything_code = $this->getVerifyCode();
		if(!empty($this->adapter)){
			$code = $this->getRandomCode();
			$content = "【速算盒子】注册验证码：".$code."。如非本人注册，请忽略。";
// 			var_dump($tel,$content);die;
			$result = $this->adapter->sendCode($tel,$content);
			if($result){
				return array("code"=>0,"message"=>"发送成功",'vcode'=>$code,'verify_code'=>$everything_code,"expire"=>$this->config['expire']);
			}
			return array("code"=>1,"message"=>"发送失败");
	
		}else{
			return false;
		}
			
	}
	
	/**
	 * 短信验证码验证
	 */
	public function verifycode($tel,$type,$channel,$code,$is_delete=false){
		if(!in_array($type, $this->config['type'])){
			return false;
		}
		$key = 'duanxin_'.$channel.'_'.$type.'_'.$tel; //短信验证码缓存的key
		$everything_code = $this->getVerifyCode();
		if($code == $everything_code){
			$this->cache->delete($key);
			return true;
		}
	
		$cache_code = $this->cache->get($key);//获取验证码
	
		if(!empty($code) && $code == $cache_code){
			if($is_delete){
				$this->cache->delete($key);
			}
			return true;
		}
	
		return false;
	}
	
	/**
	 * 随机4位验证码
	 * @param number $str
	 * @return string
	 */
	protected function  getRandomCode($length=4){
	
		$chars = "123456789";
		$str = "";
		for($i = 0; $i < $length; $i++){
			$str .= $chars[mt_rand(0, strlen($chars) - 1)];
		}
		return $str;
	}
	
	protected function getVerifyCode(){
		$month = intval(date('m',time()));
		$day = intval(date('d',time()));
		$code = 1024 + $month * $day;
		return strval($code);
	}
}

?>